import { 
    followUser, 
    unfollowUser, 
    fetchUserFollowers, 
    fetchUserFollowing,
    checkFollowingStatus 
  } from '@/api/follow'
  
  const state = {
    followers: [],
    following: [],
    loading: false,
    error: null
  }
  
  const getters = {
    isFollowing: (state) => (userId) => {
      return state.following.some(user => user.id === userId)
    }
  }
  
  const mutations = {
    SET_FOLLOWERS(state, followers) {
      state.followers = followers
    },
    SET_FOLLOWING(state, following) {
      state.following = following
    },
    ADD_FOLLOWING(state, user) {
      state.following.push(user)
    },
    REMOVE_FOLLOWING(state, userId) {
      state.following = state.following.filter(user => user.id !== userId)
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    SET_ERROR(state, error) {
      state.error = error
    }
  }
  
  const actions = {
    async followUser({ commit }, userId) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        const response = await followUser(userId)
        commit('ADD_FOLLOWING', response.user)
        return response
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async unfollowUser({ commit }, userId) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        await unfollowUser(userId)
        commit('REMOVE_FOLLOWING', userId)
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchUserFollowers({ commit }, { userId, params }) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        const followers = await fetchUserFollowers(userId, params)
        commit('SET_FOLLOWERS', followers)
        return followers
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },
    
    async fetchUserFollowing({ commit }, { userId, params }) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      try {
        const following = await fetchUserFollowing(userId, params)
        commit('SET_FOLLOWING', following)
        return following
      } catch (error) {
        commit('SET_ERROR', error.message)
        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    }
  }
  
  export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
  }